#!/usr/bin/env bash

set -e

cd "$(dirname "$0")/../.."

FRONTEND_VERSION="20250128065759"

function installFrontendFromGitHub() {
    # Temporarily disable exit on error
    set +e
    # Attempt to install the specified frontend version from GitHub
    scripts/install/pip_packages \
        --target=./custom_components/hacs \
        "https://github.com/hacs/frontend/releases/download/${FRONTEND_VERSION}/hacs_frontend-${FRONTEND_VERSION}-py3-none-any.whl"
    # Re-enable exit on error
    set -e
}

function installFrontend() {
    # Remove existing frontend installation
    rm -rf ./custom_components/hacs/hacs_frontend
    installFrontendFromGitHub

    # Check if the installation from GitHub was successful
    if [[ ! -f "./custom_components/hacs/hacs_frontend/version.py" ]]; then
        echo "Failed to install from GitHub, trying PyPI"
        # If not, install from PyPI
        scripts/install/pip_packages \
            --target=./custom_components/hacs \
            "hacs_frontend==${FRONTEND_VERSION}"
    fi

    # Clean up any leftover metadata files
    rm -rf ./custom_components/hacs/*.dist-info
}

# Get current version if any
CURRENT_VERSION=$(grep "VERSION" ./custom_components/hacs/hacs_frontend/version.py -s | cut -d '"' -f 2)

# Install the frontend if the current version is different from the desired version
if [[ "${CURRENT_VERSION}" != "${FRONTEND_VERSION}" ]]; then
    installFrontend
else
    echo "Frontend version is the same (${FRONTEND_VERSION}), skipping download"
fi
